package de.tewdreyer.android.quaffed;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MealOpenHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "quaffed";
    private static final int DATABASE_VERSION = 2;
    private static final String MEAL_TABLE_NAME = "meal";
    private static final String MEAL_TABLE_ID_LABEL = "id";
    private static final String MEAL_TABLE_ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT";
    private static final String MEAL_TABLE_ID = MEAL_TABLE_ID_LABEL + " " + MEAL_TABLE_ID_TYPE;
    private static final String MEAL_TABLE_DATE_LABEL = "date";
    private static final String MEAL_TABLE_DATE_TYPE = "DATE";
    private static final String MEAL_TABLE_DATE = MEAL_TABLE_DATE_LABEL + " " + MEAL_TABLE_DATE_TYPE;
    private static final String MEAL_TABLE_VOLUME_LABEL = "volume";
    private static final String MEAL_TABLE_VOLUME_TYPE = "INTEGER";
    private static final String MEAL_TABLE_VOLUME = MEAL_TABLE_VOLUME_LABEL + " " + MEAL_TABLE_VOLUME_TYPE;
    private static final String MEAL_TABLE_CREATE = String.format("CREATE TABLE %s (%s,%s,%s);", MEAL_TABLE_NAME,
            MEAL_TABLE_ID,
            MEAL_TABLE_DATE,
            MEAL_TABLE_VOLUME);

    MealOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(MEAL_TABLE_CREATE);
    }

    public void insert(String date, int volume) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(MEAL_TABLE_DATE_LABEL, date);
        values.put(MEAL_TABLE_VOLUME_LABEL, volume);
        db.insert(MEAL_TABLE_NAME, null, values);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public Cursor all(Activity activity) {
        String[] from = {MEAL_TABLE_ID_LABEL, MEAL_TABLE_DATE_LABEL, MEAL_TABLE_VOLUME_LABEL};
        String order = MEAL_TABLE_DATE_LABEL;
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(MEAL_TABLE_NAME, null, null, null, null, null, order, null);
        activity.startManagingCursor(cursor);
        return cursor;
    }
}